package com.example.service;


import com.example.entity.Discuss;
import com.example.mapper.DiscussMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DiscussService{

    @Resource
    private DiscussMapper discussMapper;

    public void addDiscuss(Discuss discuss) {
        discuss.setCreateTime(new Timestamp(System.currentTimeMillis()));
        discussMapper.insertDiscuss(discuss);
    }

    public List<Map<String, Object>> getCommentsByPostId(Long nid) {
        // 1. 获取所有评论
        List<Map<String, Object>> allComments = discussMapper.getCommentsByPostId(nid);

        // 2. 将评论组织成树形结构
        List<Map<String, Object>> result = new ArrayList<>();
        Map<Integer, Map<String, Object>> commentMap = new HashMap<>();

        // 先找出所有父评论
        for (Map<String, Object> comment : allComments) {
            if (comment.get("lastId") == null) {
                comment.put("replies", new ArrayList<>());
                result.add(comment);
                commentMap.put((Integer) comment.get("discussId"), comment);
            }
        }

        // 将子评论添加到对应的父评论下
        for (Map<String, Object> comment : allComments) {
            Integer lastId = (Integer) comment.get("lastId");
            if (lastId != null) {
                Map<String, Object> parentComment = commentMap.get(lastId);
                if (parentComment != null) {
                    ((List<Map<String, Object>>) parentComment.get("replies")).add(comment);
                }
            }
        }
        return result;
    }

    public void updateDiscuss(Discuss discuss) {
        discussMapper.updateDiscuss(discuss);
    }

    public void deleteDiscuss(Long id) {
        discussMapper.deleteDiscuss(id);
    }

    public List<Discuss> getAllComments() {
        return discussMapper.selectAllComments();
    }

    public PageInfo<Discuss> selectPage(Discuss discuss, Integer pageNum, Integer pageSize) {
        // 开始分页
        PageHelper.startPage(pageNum, pageSize);

        // 调用 Mapper 查询数据
        List<Discuss> list = discussMapper.selectAllComments();

        // 返回分页信息
        return new PageInfo<>(list);
    }

}


